<template>
  <div>
    <!-- 主要表格区 -->
    <div class="main_table_area">
      <!-- 操作 -->
      <div class="op_btns">
        <!-- 上传 -->
        <div class="upload_container">
          <el-upload multiple :show-file-list="false" :action="mainTable.upload.action" :name="mainTable.upload.name"
            :headers="mainTable.upload.headers" :before-upload="beforeUploadHandle" :on-success="successHandle"
            :on-error="errorHandle">
            <el-button size="mini" type="success" :icon="imageAuths.uploadImage.iconClass"
              v-show="uploadImageStatus">上传图片</el-button>
          </el-upload>
        </div>
        <!-- 批量删除 -->
        <el-button size="mini" type="danger" :icon="imageAuths.deleteImages.iconClass" @click="toDeleteBatch"
          v-show="deleteImagesStatus">批量删除选中图片</el-button>
      </div>
      <div>
        <el-table :data="mainTable.data" border highlight-current-row size="mini"
          @selection-change="selectionChangeHandle">
          <template slot="empty">
            <el-empty description="什么图片都没有"></el-empty>
          </template>
          <!-- 复选列 -->
          <el-table-column type="selection"></el-table-column>
          <!-- 序号列 -->
          <el-table-column type="index" label="序号"></el-table-column>
          <!-- 展开列 -->
          <el-table-column type="expand" label="详情">
            <template slot-scope="{row}">
              <el-descriptions :title="row.originalFileName" :column="1" border size="small">
                <el-descriptions-item :label="col.label" v-for="col in mainTable.expandColumns" :key="col.id">
                  <span>{{ row[col.prop] }}</span>
                </el-descriptions-item>
              </el-descriptions>
            </template>
          </el-table-column>
          <!-- 动态列 -->
          <el-table-column show-overflow-tooltip v-for="(col, index) in mainTable.columns" :key="index" :prop="col.prop"
            :label="col.label" :sortable="col.sortable" :min-width="col.minWidth">
          </el-table-column>
          <!-- 操作列 -->
          <el-table-column width="200px" label="操作">
            <template slot-scope="{row}">
              <el-button plain size="mini" type="primary" icon="el-icon-picture-outline-round"
                @click="toSeeSelected(row)">
                查看
              </el-button>
              <el-button plain size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div style="display: flex;justify-content:space-around">
          <el-pagination hide-on-single-page layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="mainTable.page.currentPage" :page-size="mainTable.page.pageSize" :total="mainTable.page.total">
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 图片查看抽屉 -->
    <div>
      <el-drawer show-close modal :title="imageDrawer.playing.originalFileName" direction="ttb"
        :before-close="beforeDisplayCloseHandle" :visible="imageDrawer.visible" size="100%">
        <img :src="imageDrawer.playing.visitUrl" :title="imageDrawer.playing.originalFileName">
      </el-drawer>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      // 主表数据
      mainTable: {
        // 动态列
        columns: [
          {
            prop: 'originalFileName',
            label: '原名',
            sortable: false,
            minWidth: '80px',
          },
          {
            prop: 'size',
            label: '大小(Kb)',
            sortable: true,
            minWidth: '80px',
          },
          {
            prop: 'createAt',
            label: '上传时间',
            sortable: true,
            minWidth: '70px',
          },
        ],
        // 展开列
        expandColumns: [
          {
            prop: 'id',
            label: 'ID',
          },
          {
            prop: 'storeAbsolutePath',
            label: '存储位置',
          },
          {
            prop: 'visitUrl',
            label: '访问地址',
          },
          {
            prop: 'mimePrefix',
            label: '类型',
          },
          {
            prop: 'size',
            label: '大小(Kb)',
          },
          {
            prop: 'extend',
            label: '后缀',
          },
          {
            prop: 'originalFileName',
            label: '原名',
          },
          {
            prop: 'storeFileName',
            label: '存储名',
          },
          {
            prop: 'createAt',
            label: '上传时间',
          },
          {
            prop: 'creatorName',
            label: '上传者',
          },
          {
            prop: 'updateAt',
            label: '更新时间',
          },
          {
            prop: 'updaterName',
            label: '更新者',
          },
        ],
        // 表格数据
        data: [],
        // 表格选中数据
        selectedData: [],
        // 分页
        page: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        // 上传图片
        upload: {
          // 上传接口
          action: `${this.$axios.defaults.baseURL}admin/file/image`,
          // 参数名
          name: 'file',
          // 请求头
          headers: {
            token: sessionStorage.getItem('token'),
          },
        },
      },

      // 图片预览抽屉
      imageDrawer: {
        // 抽屉可见性
        visible: false,
        // 预览中图片
        playing: {
          visitUrl: '',
          originalFileName: '',
        },
      },
    }
  },

  computed: {
    // 借助生成计算属性：uiAuthValidateIsNotNeeded、imageAuths
    ...mapGetters('uiAuthModule', ['uiAuthValidateIsNotNeeded', 'imageAuths']),

    // 各个操作的可用状态
    uploadImageStatus() {
      const { uploadImage: { finalStatus } } = this.imageAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    deleteImagesStatus() {
      const { deleteImages: { finalStatus } } = this.imageAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    getImagesStatus() {
      const { getImages: { finalStatus } } = this.imageAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    }
  },

  methods: {
    //#region 主表方法开始
    // 批量删除
    async toDeleteBatch() {
      const fileDTOList = this.mainTable.selectedData.map(m => { return { "id": m.id, 'storeAbsolutePath': m.storeAbsolutePath } })
      if (fileDTOList.length <= 0) {
        this.$message.info('请勾选要删除的图片!')
        return
      } else {
        try {
          await this.$confirm(`确定删除 ${fileDTOList.length} 张图片吗`)
          const { data: res } = await this.$axios({
            method: 'delete',
            url: '/admin/file/image/batch',
            data: fileDTOList,
          })
          if (res.code === 0) {
            this.$message.error(res.msg)
            return
          }
          this.$message.success(`已删除 ${res.data} 张图片`)
          this.mainTable.page.currentPage = 1
          this.pagingGetImages()
        } catch (e) {
          if (e === 'cancel') {
            this.$message.info(`取消删除`)
            return
          }
          this.$message.error(e.msg)
        }
      }
    },
    // 表格复选
    selectionChangeHandle(selection) {
      this.mainTable.selectedData = selection
    },
    // 查看选中图片
    toSeeSelected(image) {
      this.imageDrawer.playing = image
      this.imageDrawer.visible = true
    },
    // 隐藏图片抽屉
    beforeDisplayCloseHandle(done) {
      this.imageDrawer.visible = false
      done()
    },
    // 分页获取数据
    async pagingGetImages() {
      try {
        const { data: res } = await this.$axios.get(`/admin/file/image/${this.mainTable.page.currentPage}/${this.mainTable.page.pageSize}`)
        if (res.code === 0) {
          this.$message.error(res.msg)
          return
        }
        this.mainTable.data = res.data.data
        this.mainTable.page.total = res.data.total
      } catch (error) {
        console.dir(error)
      }
    },
    // 分页组件参数变化处理
    handleSizeChange(pageSize) {
      this.mainTable.page.pageSize = pageSize
      this.pagingGetImages()
    },
    handleCurrentChange(currentPage) {
      this.mainTable.page.currentPage = currentPage
      this.pagingGetImages()
    },
    //#endregion 主表方法结束

    //#region 图片删除方法开始
    // 成功回调
    successHandle(response, file) {
      if (response.code === 0) {
        this.$message.error(response.msg)
        return
      }
      this.$message.success(`${file.name}${response.msg}`)
      this.pagingGetImages()
    },
    // 失败回调
    errorHandle(err, file) {
      this.$message.error(file.name + err.msg)
    },
    // 上传检测，返回true表名能够上传，false不能上传
    beforeUploadHandle(file) {
      if (!/^image/i.test(file.type)) {
        this.$message.warning(`只能上传图片,文件类型为 ${file.name.substr(file.name.lastIndexOf('.') + 1)}`)
        return false
      }
      return true
    }
    //#endregion 图片删除方法结束
  },

  // 钩子
  mounted() {
    // 如果能够查询图片
    if (this.getImagesStatus) {
      this.pagingGetImages()
    }
  }
}
</script>

<style lang="less" scoped>
.main_table_area {
  .op_btns {
    display: flex;
    justify-content: start;
    padding: 0 0 10px 0;

    .upload_container {
      display: inline-block;
      margin-right: 10px;
    }
  }
}


img {
  display: block;
  height: 86vh;
  box-sizing: border-box;
  border: 1px solid gray;
  margin: 0 auto;
}
</style>